<script setup lang="ts">
import { ref, reactive, h } from "vue";
import { DynamicTable } from "@/components/DynamicTable";
import { PaginationConfig, TableColumn } from "@/components/DynamicTable/types";
import DynamicForm from "@/components/DynamicForm/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import { FormItemConfig } from "@/components/DynamicForm/types";
import { ElMessage, ElButton, ElCheckbox, ElCheckboxGroup } from "element-plus";
import { Refresh } from "@element-plus/icons-vue";
import { searchBeian, saveBeian } from "../servers";

const props = defineProps<{
  task: string;
}>();

const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 20,
  total: 0,
  pageSizes: [20, 50, 100],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

const loading = ref(false);
const searchFormRef = ref<DynamicFormInstance>();

const searchForm = reactive({
  type: "web", // 默认web
  keyword: "",
});

const searchConfig: FormItemConfig[] = [
  {
    key: "type",
    name: "备案类型",
    type: "select",
    placeholder: "选择备案类型",
    // col: { span: 4 },
    params: {
      clearable: false,
      showPlaceholder: false,
      options: [
        { label: "网站域名(web)", value: "web" },
        { label: "移动应用(app)", value: "app" },
        { label: "微信小程序(mapp)", value: "mapp" },
      ],
    },
  },
  {
    key: "keyword",
    name: "关键词",
    type: "input",
    placeholder: "请输入域名/企业名称/备案号",
    col: { span: 6 },
    params: {
      clearable: true,
    },
  },
];

const columns = ref<TableColumn[]>([
  {
    label: "选择",
    prop: "selected",
    width: 80,
    show: true,
    slot: "selection",
  },
  {
    label: "域名",
    prop: "domain",
    minWidth: 200,
    show: true,
  },
  {
    label: "主办单位",
    prop: "unitName",
    minWidth: 200,
    show: true,
  },
  {
    label: "主体备案号",
    prop: "mainLicence",
    width: 180,
    show: true,
  },
  {
    label: "服务备案号",
    prop: "serviceLicence",
    width: 180,
    show: true,
  },
  {
    label: "单位性质",
    prop: "natureName",
    width: 120,
    show: true,
  },
  {
    label: "内容类型",
    prop: "contentTypeName",
    width: 120,
    show: true,
  },
  {
    label: "记录时间",
    prop: "updateRecordTime",
    width: 120,
    show: true,
  },
]);

const searchResults = ref<any[]>([]);
const selectedRecords = ref<any[]>([]);

const handleSearch = async (value: any) => {
  if (!value.keyword) {
    ElMessage.warning("请输入关键词");
    return;
  }

  loading.value = true;
  try {
    const params = {
      type: value.type || "web",
      keyword: value.keyword,
      page: pagination.currentPage,
      size: pagination.pageSize,
    };
    const { data } = await searchBeian(params);
    searchResults.value = data.list || [];
    pagination.total = data.total || 0;
  } catch (error) {
    ElMessage.error("查询失败");
  } finally {
    loading.value = false;
  }
};

const handleSearchReset = () => {
  searchFormRef.value?.resetFields();
  searchResults.value = [];
  selectedRecords.value = [];
  pagination.total = 0;
};

const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  handleSearch(searchForm);
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  handleSearch(searchForm);
};

const handleSelectChange = (selectedRows: any[]) => {
  selectedRecords.value = selectedRows;
};

const handleSaveSelected = async () => {
  if (selectedRecords.value.length === 0) {
    ElMessage.warning("请选择要保存的记录");
    return;
  }

  try {
    // 将搜索结果的字段转换为保存接口需要的格式
    const records = selectedRecords.value.map((item) => ({
      domain: item.domain,
      unitName: item.unitName,
      mainLicence: item.mainLicence,
      serviceLicence: item.serviceLicence,
      natureName: item.natureName,
      contentTypeName: item.contentTypeName,
      updateRecordTime: item.updateRecordTime,
      leaderName: item.leaderName,
      limitAccess: item.limitAccess,
      domainId: item.domainId,
      mainId: item.mainId,
      serviceId: item.serviceId,
    }));

    await saveBeian({
      type: searchForm.type,
      records: records,
    });

    ElMessage.success(`成功保存 ${selectedRecords.value.length} 条记录`);
    selectedRecords.value = [];
  } catch (error) {
    ElMessage.error("保存失败");
  }
};
</script>

<template>
  <div>
    <el-card shadow="never">
      <DynamicForm
        ref="searchFormRef"
        v-model="searchForm"
        :form-config="searchConfig"
        :gutter="16"
        label-width="100px"
        type="search"
        @search="handleSearch"
        @reset="handleSearchReset"
      />
    </el-card>

    <div style="height: 10px"></div>

    <el-card>
      <DynamicTable
        :pagination="pagination"
        :columns="columns"
        :data="searchResults"
        :loading="loading"
        selection-type="multiple"
        @current-page-change="handlePageChange"
        @size-change="handleSizeChange"
        @selection-change="handleSelectChange"
      >
        <template #toolbar-left>
          <el-button
            type="primary"
            @click="handleSaveSelected"
            :disabled="selectedRecords.length === 0"
          >
            批量保存 ({{ selectedRecords.length }})
          </el-button>
        </template>

        <template #toolbar-right>
          <el-button type="success" :icon="Refresh" @click="handleSearchReset">
            清空
          </el-button>
        </template>
      </DynamicTable>
    </el-card>
  </div>
</template>

<style scoped lang="scss"></style>
